from functools import wraps
from time import time
from jwt import decode as jwt_decode
from utils import respond, ERRORCODES
from flask import request
from config import Config


def auth_required(token_verification=True):
    """
    装饰需要鉴权的视图函数。
    """

    def decorator(func):
        @wraps(func)
        def decorated(*args, **kwargs):
            token = request.headers["Authorization"].removeprefix("Bearer ")
            if not token:
                return respond(None, "缺少参数。", ERRORCODES.BAD_REQUEST)
            elif token_verification:
                try:
                    data = jwt_decode(token, Config.JWT_SECRET_KEY, algorithm="HS256")
                    if data["exp"] < int(time()):
                        return respond(None, "token已过期。", ERRORCODES.UNAUTHORIZED)
                except Exception:
                    return respond(None, "无效的token。", ERRORCODES.UNAUTHORIZED)
            return func(*args, **kwargs)

        return decorated

    return decorator
